﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin.BuilderProperties;
using Microsoft.Owin.Diagnostics;
using Owin;

namespace WebApiDemoOwinSelfHost
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ServicePointManager.DefaultConnectionLimit = short.MaxValue;
            var configuration = new HttpConfiguration();
            configuration.MapHttpAttributeRoutes();
            configuration.EnsureInitialized();
            configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            //configuration.Filters.Add(new LogExceptionFilterAttribute());
            configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            app.UseWebApi(configuration);
            //app.Use(async (context, next) =>
            //{

            //    using (MethodMonitor.New(context.Request.Path.ToString()))
            //    {
            //        await next();
            //    }
            //});
            app.Run((owinContext) =>
            {
                owinContext.Response.ContentType = "text/plain";
                return owinContext.Response.WriteAsync("welcome");
            });
            //注册当owin 框架资源卸载时执行的操作
            var properties = new AppProperties(app.Properties);
            var token = properties.OnAppDisposing;
            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    //todo:
                });
            }
            app.UseErrorPage(new ErrorPageOptions { ShowExceptionDetails = true });


            //#if DEBUG
            //            app.UseErrorPage();
            //#endif
            //            app.UseWelcomePage("/");
        }
    }
}
